package org.jl.main.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.Map;

public class UtilForJson {

    public static String toString(@NonNull Object obj) {
        return toString(obj, false, false);
    }

    public static String toString(@NonNull Object obj, boolean isFormat) {
        return toString(obj, isFormat, false);
    }

    /**
     * 对象转字符串
     *
     * @param obj       对象
     * @param isFormat  是否格式化
     * @param underline 是否下划线，注仅在对象为Bean时有效
     * @return String
     */
    public static String toString(@NonNull Object obj, boolean isFormat, boolean underline) {
        ObjectMapper mapper = new ObjectMapper();
        if (underline) {
            mapper.setPropertyNamingStrategy(new PropertyNamingStrategies.SnakeCaseStrategy());
        }
        try {
            if (isFormat) {
                return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            } else {
                return mapper.writeValueAsString(obj);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    @SuppressWarnings("unchecked")
    public static Map<String, Object> toMap(@NonNull String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonStr, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toBean(@NonNull String jsonStr, Class<T> clazz, @NonNull boolean underline) {
        ObjectMapper mapper = new ObjectMapper();
        if (underline) {
            mapper.setPropertyNamingStrategy(new PropertyNamingStrategies.SnakeCaseStrategy());
        }
        try {
            return mapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> toList(@NonNull String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(jsonStr, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
